`timescale 1ns / 1ps
/*
 Copyright 2020 Sean Xiao, jxzsxsp@qq.com
 
 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at
 
 http://www.apache.org/licenses/LICENSE-2.0
 
 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

module pc_uart #(
   parameter MAIN_CLK = 50
)
(
    input  clk,
    
    input  rxd,
    output txd,

    output reg code_wea = 0,
    output reg [11:0] code_addr = 0,
    output reg [31:0] code_din = 0,

    input  txd_start,
    input  [7:0] txd_data,
    output txd_done,
    
    output rxd_done,
    
    input  reset
);
//=======================================================

wire rxd_rdy;
wire [7:0] rxd_data;
wire rxd_eop;



wire [9:0] baudtick = (MAIN_CLK == 100) ? 109 : (MAIN_CLK == 80) ? 87 : 54;
uart_transceiver  uart_transceiver_inst
(
    .sys_clk    (clk), // 100m

    .uart_rx    (rxd),
    .uart_tx    (txd),

    .divisor    (baudtick),  // 115200 * 8 

    .rx_data    (rxd_data),
    .rx_done    (rxd_rdy),
    .rx_eop     (rxd_eop),

    .tx_data    (txd_data),
    .tx_wr      (txd_start),
    .tx_done    (txd_done),
    .tx_busy    (),

    .test_pin   (),

    .sys_rst    (reset)
);

//=======================================================

reg [3:0] rx_st = 0;
always @ (posedge clk)
if(reset | rxd_eop)
begin
    rx_st <= 0;
end 
else case (rx_st)
0:
begin
    code_wea <= 0;
    code_addr <= 0;
    rx_st <= 1;
end
1:
begin
    if(rxd_rdy) 
    begin
        code_din <= {rxd_data, code_din[31:08]};
        rx_st <= 2;
    end
end
2:
begin
    if(rxd_rdy) 
    begin
        code_din <= {rxd_data, code_din[31:08]};
        rx_st <= 3;
    end
end
3:
begin
    if(rxd_rdy) 
    begin
        code_din <= {rxd_data, code_din[31:08]};
        rx_st <= 4;
    end
end
4:
begin
    if(rxd_rdy) 
    begin
        code_din <= {rxd_data, code_din[31:08]};
        code_wea <= 1;
        rx_st <= 5;
    end
end
5:
begin
    code_wea <= 0;
    rx_st <= 6;
end
6:
begin
    code_addr <= code_addr + 1;
    rx_st <= 1; 
end
default : rx_st <= 0;
endcase

//=======================================================

assign rxd_done = rxd_eop;

//=======================================================

endmodule
